﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ProgNetComponents.Validation.Rules

{
    /// <summary>
    /// Rule for checking if at least one of columns is not null
    /// </summary>
    public class AnyOfColumnsRequiredValidationRule : MultiColumnsValidationRule
    {
        #region Static
        /// <summary>
        /// Initializes the <see cref="AnyOfColumnsRequiredValidationRule" /> class.
        /// </summary>
        static AnyOfColumnsRequiredValidationRule()
        {
            GlobalDefaultErrorString = "Przynajmniej jedna z tych wartości jest wymagana.";
        }
        /// <summary>
        /// Gets or sets the global default error string.
        /// </summary>
        /// <value>
        /// The global default error string.
        /// </value>
        public static string GlobalDefaultErrorString { get; set; }
        #endregion

        #region Properties

        /// <summary>
        /// Gets default error string
        /// </summary>
        /// <value>
        /// The default error string.
        /// </value>
        protected override string DefaultErrorString
        {
            get
            {
                return GlobalDefaultErrorString;
            }
        }
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="AnyOfColumnsRequiredValidationRule" /> class.
        /// </summary>
        public AnyOfColumnsRequiredValidationRule()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AnyOfColumnsRequiredValidationRule" /> class.
        /// </summary>
        /// <param name="columns">The columns.</param>
        /// <param name="error">The error.</param>
        public AnyOfColumnsRequiredValidationRule(string[] columns, string error = null)
            : base(columns, error)
        {

        }

        /// <summary>
        /// Validates data row
        /// </summary>
        /// <param name="row">The row.</param>
        /// <returns></returns>
        protected override bool DoValidate(DataRow row)
        {
            bool result = true;
            foreach (string column in Columns)
            {
                if (row.GetColumnValue(column).IsNull())
                {
                    result = false;
                }
                else
                {
                    result = true;
                    break;
                }
            }
            if (!result)
            {
                SetColumnsErrors(row, ErrorString);
            }
            return result;
        }
    }
}
